# -*- coding:utf-8 -*-
import os,sys
import time
from datetime import datetime
import traceback
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
from CommonLib.mylog import mylog
from DataSupport.SinaMinDataSupport import SinaMinDataSupport
from DataSupport.BasicDataSupport import BasicDataSupport
from CommonLib.StockTool import StockTool


class MinDataJob:
    # 分钟级/秒级数据的定时任务
    def __init__(self):
        pass

	# crontab决定启动时间和杀死时间
	# 本脚本实现交易日判断
    def process(self):
		log = mylog('Crontab.MinDataJob', None)
		date = datetime.today().strftime('%Y-%m-%d')
		# 判断交易日
		obj = StockTool()
		flag, all_trade_date = obj.get_trade_date()
		if flag is False:
			log.info('get trade date faild')
			return False, 'get trade date faild'
		if date not in all_trade_date:
			log.info('not trade date')
			return True, 'not trade date'
		try:
			obj = SinaMinDataSupport()
			while True:	
				# 午休时间空循
				cur_time = datetime.today().strftime('%X')
				while cur_time > '11:35:00' and cur_time < '12:55:00':
					time.sleep(30)
					cur_time = datetime.today().strftime('%X')
					continue
				# 正常工作时间
				flag, msg = obj.get_data(mode = 'stock')
				if flag is True:
					flag, msg = obj.store_data(msg, date=date)
					if flag is False:
						log.error(msg)
				else:
					log.error(msg)
					# 发生数据获取错误时，休息10秒
					time.sleep(10)
				flag, msg = obj.get_data(mode = 'index')
				if flag is True:
					flag, msg = obj.store_data(msg, date=date)
					if flag is False:
						log.error(msg)
				else:
					log.error(msg)
					time.sleep(10)
				time.sleep(15)
		except:
			log.error(traceback.format_exc())

if __name__ == '__main__':
    obj = MinDataJob()
    obj.process()
